<?php

/* 引用全局定义 */
require __DIR__ . '/common_global.php';
/* 商品相关调用 */
require __DIR__ . '/common_goods.php';
/* 图片上传、生成缩略图、删除等操作调用 */
require __DIR__ . '/common_upload.php';
/* 新增 */
require __DIR__ . '/common_new.php';

use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use think\Session;

#极光推送
use JPush\Client as JPush;
use JPush\Exceptions\APIConnectionException;
use JPush\Exceptions\APIRequestException;


#Uni push 推送
header("Content-Type: text/html; charset=utf-8");
require_once APP_PATH . '/../extend/UPush/IGt.Push.php';
require_once APP_PATH . '/../extend/UPush/igetui/IGt.AppMessage.php';
require_once APP_PATH . '/../extend/UPush/igetui/IGt.APNPayload.php';
require_once APP_PATH . '/../extend/UPush/IGt.Batch.php';
require_once APP_PATH . '/../extend/UPush/igetui/utils/AppConditions.php';
require_once APP_PATH . '/../extend/UPush/igetui/template/IGt.BaseTemplate.php';
require_once APP_PATH . '/../extend/UPush/igetui/template/IGt.NotificationTemplate.php';
require_once APP_PATH . '/../extend/UPush/igetui/template/IGt.LinkTemplate.php';
// require_once APP_PATH . '/../extend/UPush/igetui/template/IGt.StartActivityTemplate.php';
require_once APP_PATH . '/../extend/UPush/igetui/template/IGt.TransmissionTemplate.php';

define('HOST', 'http://sdk.open.api.igexin.com/apiex.htm');
define('APPID', 'i6XvO8bCH57dTLVrOHkQq');
define('APPKEY', 'DiwSO2BSzr8ACFFL4Jjdv5');
define('MASTERSECRET', '6zfP4n32YJAFQ9yEfoqdm9');
define('CID', '93ebd7c24cb42061c87aa48b97d3609e');

#群推推送
function pushMessageToApp($title, $content)
{
    $igt = new IGeTui(HOST, APPKEY, MASTERSECRET);
    // STEP2：选择通知模板   （透传 = 自定义）
    //定义透传模板，设置透传内容，和收到消息是否立即启动启用  
    $template = IGtNotificationTemplateDemo($title, $content);
    // STEP5：定义"AppMessage"类型消息对象，设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)

    $message = new IGtAppMessage();
    $message->set_isOffline(true);
    $message->set_offlineExpireTime(10 * 60 * 1000);
    $message->set_data($template);

    $appIdList = array(APPID);

    $message->set_appIdList($appIdList);
    //$message->set_conditions($cdt->getCondition());
    // STEP6：执行推送
    $rep = $igt->pushMessageToApp($message, "任务组名");

    // var_dump($rep);
    // echo ("<br><br>");
}

//单推接口
function pushMessageToSingle($title, $cid, $content)
{
    $igt = new IGeTui(HOST, APPKEY, MASTERSECRET);

    //消息模版：
    // 4.NotyPopLoadTemplate：通知弹框下载功能模板
    $template = IGtNotyPopLoadTemplateDemo($title, $content);

    //定义"SingleMessage"
    $message = new IGtSingleMessage();
    $message->set_isOffline(true);//是否离线
    $message->set_offlineExpireTime(3600 * 12 * 1000);//离线时间
    $message->set_data($template);//设置推送消息类型

    //$message->set_PushNetWorkType(0);//设置是否根据WIFI推送消息，2为4G/3G/2G，1为wifi推送，0为不限制推送
    //接收方
    $target = new IGtTarget();
    $target->set_appId(APPID);
    $target->set_clientId($cid);
//    $target->set_alias(Alias);

    try {
        $rep = $igt->pushMessageToSingle($message, $target);
        // var_dump($rep);
        // exit;

        // echo("<br><br>");

    } catch (RequestException $e) {
        $requstId = e . getRequestId();
        //失败时重发
        $rep = $igt->pushMessageToSingle($message, $target, $requstId);

        // var_dump($rep);
        echo("<br><br>");
    }
}

# 群推 单推 模板  （透传 = 自定义）
function IGtNotyPopLoadTemplateDemo($title, $content)
{
    $template = new IGtNotificationTemplate();

    // 设置APPID与APPKEY 
    $template->set_appId(APPID);                   //应用appid
    $template->set_appkey(APPKEY);                 //应用appkey

    //设置模板参数
    $template->set_transmissionType(1);            //透传消息类型
    $template->set_transmissionContent("小邹测试12");//透传内容
    $template->set_title($title);      //通知栏标题
    $template->set_text($content);     //通知栏内容
    $template->set_logo("http://33wang.douyinhot.com/46f5b202003131520417317.png");                       //通知栏logo
    $template->set_logoURL("https://www.baidu.com");                    //通知栏logo链接
    //STEP4：设置响铃、震动等推送效果
    $template->set_isRing(true);                   //是否响铃
    $template->set_isVibrate(true);                //是否震动
    $template->set_isClearable(true);              //通知栏是否可清除

    return $template;
}

#应用首页
function IGtNotificationTemplateDemo($title, $content)
{
    $template = new IGtNotificationTemplate();
    $template->set_appId(APPID);                      //应用appid
    $template->set_appkey(APPKEY);                    //应用appkey
    $template->set_transmissionType(1);               //透传消息类型
    $template->set_transmissionContent("测试离线2");   //透传内容
    $template->set_title($title);                     //通知栏标题
    $template->set_text($content);                    //通知栏内容
    $template->set_logo("logo.png");                  //通知栏logo
    $template->set_logoURL("http://wwww.igetui.com/logo.png"); //通知栏logo链接
    $template->set_isRing(true);                      //是否响铃
    $template->set_isVibrate(true);                   //是否震动
    $template->set_isClearable(true);                 //通知栏是否可清除
    //$template->set_duration(BEGINTIME,ENDTIME); //设置ANDROID客户端在此时间区间内展示消息
    $template->set_channel("set_channel");
    $template->set_channelName("set_channelName");
    $template->set_channelLevel(3);
    $template->set_notifyId(12345678);
    return $template;
}

#打开应用内页
function IGtStartActivityTemplateDemo($title, $content)
{
    $template = new IGtStartActivityTemplate();
    $template->set_appId(APPID);//应用appid
    $template->set_appkey(APPKEY);//应用appkey
    $template->set_intent("intent:#Intent;component=uni.UNI20C8902/pages/index/message;S.parm1=value1;end");
    $template->set_title($title);//通知栏标题
    $template->set_text($content);//通知栏内容
    $template->set_logo("");//通知栏logo
    $template->set_logoURL("http://*");
    $template->set_isRing(true);//是否响铃
    $template->set_isVibrate(true);//是否震动
    $template->set_isClearable(true);//通知栏是否可清除
    //$template->set_duration("XXXX-XX-XX XX:XX:XX","XXXX-XX-XX XX:XX:XX");
    // $smsMessage = new SmsMessage();//设置短信通知
    // $smsMessage->setPayload("1234");
    // $smsMessage->setUrl("http://www/getui");
    // $smsMessage->setSmsTemplateId("123456789");
    // $smsMessage->setOfflineSendtime(1000);
    // $smsMessage->setIsApplink(true);
    // $template->setSmsInfo($smsMessage);
    // $template->set_notifyId(123456543);
    return $template;
}

#查看推送结果
function getPushResult($taskId)
{
    $igt = new IGeTui(HOST, APPKEY, MASTERSECRET);
    $rep = $igt->getPushResult($taskId);
    var_dump($rep);
    exit;
}

/*
 * 更换数组的键值 为了应对 ->key
 */

function ds_change_arraykey($array, $key)
{
    $data = array();
    foreach ($array as $value) {
        $data[$value[$key]] = $value;
    }
    return $data;
}

/**
 *
 * @param type $table 数据表
 * @param type $field 条件对应的字段
 * @param type $name 条件对应的值
 * @param type $value 数值
 * @return type
 */
function ds_getvalue_byname($table, $field, $name, $value)
{
    return db($table)->where($field, $name)->value($value);
}

/*
 * 编辑器内容
 */

function build_editor($params = array())
{
    $name = isset($params['name']) ? $params['name'] : null;
    $theme = isset($params['theme']) ? $params['theme'] : 'normal';
    $content = isset($params['content']) ? $params['content'] : null;
    //http://fex.baidu.com/ueditor/#start-toolbar
    /* 指定使用哪种主题 */
    $themes = array(
        'normal' => "[   
           'fullscreen', 'source', '|', 'undo', 'redo', '|',   
           'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',   
           'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',   
           'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',   
           'directionalityltr', 'directionalityrtl', 'indent', '|',   
           'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',   
           'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',   
           'emotion',  'map', 'gmap',  'insertcode', 'template',  '|',   
           'horizontal', 'date', 'time', 'spechars', '|',   
           'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',   
           'searchreplace', 'help', 'drafts', 'charts'
       ]", 'simple' => " ['fullscreen', 'source', 'undo', 'redo', 'bold']",
    );
    switch ($theme) {
        case 'simple':
            $theme_config = $themes['simple'];
            break;
        case 'normal':
            $theme_config = $themes['normal'];
            break;
        default:
            $theme_config = $themes['normal'];
            break;
    }
    /* 配置界面语言 */
    switch (config('default_lang')) {
        case 'zh-cn':
            $lang = PLUGINS_SITE_ROOT . '/ueditor/lang/zh-cn/zh-cn.js';
            break;
        case 'en-us':
            $lang = PLUGINS_SITE_ROOT . '/ueditor/lang/en/en.js';
            break;
        default:
            $lang = PLUGINS_SITE_ROOT . '/ueditor/lang/zh-cn/zh-cn.js';
            break;
    }
    $include_js = '<script type="text/javascript" charset="utf-8" src="' . PLUGINS_SITE_ROOT . '/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="' . PLUGINS_SITE_ROOT . '/ueditor/ueditor.all.min.js""> </script><script type="text/javascript" charset="utf-8" src="' . $lang . '"></script>';
    $content = json_encode($content);
    $str = <<<EOT
$include_js
<script type="text/javascript">
var ue = UE.getEditor('{$name}',{
    toolbars:[{$theme_config}],
        });
    if($content){
ue.ready(function() {
       this.setContent($content);	
})
   }
      
</script>
EOT;
    return $str;
}

/**
 *
 * @param  $code 100000表示为正确,其他为错误代码
 * @param  $message  提示消息
 * @param  $result  返回数据
 */
function ds_json_encode($code, $message = '', $result = '', $url = '')
{
    $data = array('code' => $code, 'message' => $message, 'result' => $result, 'url' => $url);
    if (!empty($_GET['callback'])) {
        echo $_GET['callback'] . '(' . json_encode($data) . ')';
    } else {
        echo json_encode($data);
    }
    exit;
}

/**
 *p打印
 */
function p($data)
{
    return print_r($data);
}

/**
 *v打印
 */
function v($data)
{
    return var_dump($data);
}

function checkIdCard($idcard){
    // 只能是18位
    if(strlen($idcard)!=18){
        return false;
    }
    // 取出本体码
    $idcard_base = substr($idcard, 0, 17);
    // 取出校验码
    $verify_code = substr($idcard, 17, 1);
    // 加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    // 校验码对应值
    $verify_code_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    // 根据前17位计算校验码
    $total = 0;
    for($i=0; $i<17; $i++){
        $total += substr($idcard_base, $i, 1)*$factor[$i];
    }
    // 取模
    $mod = $total % 11;
    // 比较校验码
    if($verify_code == $verify_code_list[$mod]){
        return true;
    }else{
        return false;
    }
}


/**
 * 规范数据返回函数
 * @param unknown $code
 * @param unknown $msg
 * @param unknown $data
 * @return multitype:unknown
 */
function ds_callback($code, $msg = '', $data = array())
{
    return array('code' => $code, 'msg' => $msg, 'data' => $data);
}

/**
 * 格式化字节大小
 * @param number $size 字节数
 * @param string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++)
        $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 消息提示，主要适用于普通页面AJAX提交的情况
 *
 * @param string $message 消息内容
 * @param string $url 提示完后的URL去向
 * @param stting $alert_type 提示类型 error/succ/notice 分别为错误/成功/警示
 * @param string $extrajs 扩展JS
 * @param int $time 停留时间
 */
function ds_show_dialog($message = '', $url = '', $alert_type = 'error', $extrajs = '', $time = 2)
{
    $message = str_replace("'", "\\'", strip_tags($message));

    $paramjs = null;
    if ($url == 'reload') {
        $paramjs = 'window.location.reload()';
    } elseif ($url != '') {
        $paramjs = 'window.location.href =\'' . $url . '\'';
    }
    if ($paramjs) {
        $paramjs = 'function (){' . $paramjs . '}';
    } else {
        $paramjs = 'null';
    }
    $modes = array('error' => 'alert', 'succ' => 'succ', 'notice' => 'notice', 'js' => 'js');
    $cover = $alert_type == 'error' ? 1 : 0;
    $extra = 'showDialog(\'' . $message . '\', \'' . $modes[$alert_type] . '\', null, ' . ($paramjs ? $paramjs : 'null') . ', ' . $cover . ', null, null, null, null, ' . (is_numeric($time) ? $time : 'null') . ', null);';
    $extra = '<script type="text/javascript" reload="1">' . $extra . '</script>';
    if ($extrajs != '' && substr(trim($extrajs), 0, 7) != '<script') {
        $extrajs = '<script type="text/javascript" reload="1">' . $extrajs . '</script>';
    }
    $extra .= $extrajs;
    ob_end_clean();
    @header("Expires: -1");
    @header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
    @header("Pragma: no-cache");
    @header("Content-type: text/xml; charset=utf-8");

    $string = '<?xml version="1.0" encoding="utf-8"?>' . "\r\n";
    $string .= '<root><![CDATA[' . $message . $extra . ']]></root>';
    echo $string;
    exit;
}

/**
 * 取上一步来源地址
 *
 * @param
 * @return string 字符串类型的返回结果
 */
function get_referer()
{
    return empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER'];
}

/**
 * 加密函数
 *
 * @param string $txt 需要加密的字符串
 * @param string $key 密钥
 * @return string 返回加密结果
 */
function ds_encrypt($txt, $key = '')
{
    if (empty($txt))
        return $txt;
    if (empty($key))
        $key = md5(MD5_KEY);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey = "-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $nh1 = rand(0, 64);
    $nh2 = rand(0, 64);
    $nh3 = rand(0, 64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;
    $i = 0;
    while (isset($key{$i}))
        $knum += ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key . $ch1) . $ch2 . $ikey) . $ch3), $nhnum % 8, $knum % 8 + 16);
    $txt = base64_encode(time() . '_' . $txt);
    $txt = str_replace(array('+', '/', '='), array('-', '_', '.'), $txt);
    $tmp = '';
    $j = 0;
    $k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i = 0; $i < $tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum + strpos($chars, $txt{$i}) + ord($mdKey{$k++})) % 64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp, $ch3, $nh2 % ++$tmplen, 0);
    $tmp = substr_replace($tmp, $ch2, $nh1 % ++$tmplen, 0);
    $tmp = substr_replace($tmp, $ch1, $knum % ++$tmplen, 0);
    return $tmp;
}

/**
 * 解密函数
 *
 * @param string $txt 需要解密的字符串
 * @param string $key 密匙
 * @return string 字符串类型的返回结果
 */
function ds_decrypt($txt, $key = '', $ttl = 0)
{
    if (empty($txt))
        return $txt;
    if (empty($key))
        $key = md5(MD5_KEY);

    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey = "-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $knum = 0;
    $i = 0;
    $tlen = @strlen($txt);
    while (isset($key{$i}))
        $knum += ord($key{$i++});
    $ch1 = @$txt{$knum % $tlen};
    $nh1 = strpos($chars, $ch1);
    $txt = @substr_replace($txt, '', $knum % $tlen--, 1);
    $ch2 = @$txt{$nh1 % $tlen};
    $nh2 = @strpos($chars, $ch2);
    $txt = @substr_replace($txt, '', $nh1 % $tlen--, 1);
    $ch3 = @$txt{$nh2 % $tlen};
    $nh3 = @strpos($chars, $ch3);
    $txt = @substr_replace($txt, '', $nh2 % $tlen--, 1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key . $ch1) . $ch2 . $ikey) . $ch3), $nhnum % 8, $knum % 8 + 16);
    $tmp = '';
    $j = 0;
    $k = 0;
    $tlen = @strlen($txt);
    $klen = @strlen($mdKey);
    for ($i = 0; $i < $tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars, $txt{$i}) - $nhnum - ord($mdKey{$k++});
        while ($j < 0)
            $j += 64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-', '_', '.'), array('+', '/', '='), $tmp);
    $tmp = trim(base64_decode($tmp));

    if (preg_match("/\d{10}_/s", substr($tmp, 0, 11))) {
        if ($ttl > 0 && (time() - substr($tmp, 0, 11) > $ttl)) {
            $tmp = null;
        } else {
            $tmp = substr($tmp, 11);
        }
    }
    return $tmp;
}


/**
 * 获取文件列表(所有子目录文件)
 *
 * @param string $path 目录
 * @param array $file_list 存放所有子文件的数组
 * @param array $ignore_dir 需要忽略的目录或文件
 * @return array 数据格式的返回结果
 */
function read_file_list($path, &$file_list, $ignore_dir = array())
{
    $path = rtrim($path, '/');
    if (is_dir($path)) {
        $handle = @opendir($path);
        if ($handle) {
            while (false !== ($dir = readdir($handle))) {
                if ($dir != '.' && $dir != '..') {
                    if (!in_array($dir, $ignore_dir)) {
                        if (is_file($path . '/' . $dir)) {
                            $file_list[] = $path . '/' . $dir;
                        } elseif (is_dir($path . '/' . $dir)) {
                            read_file_list($path . '/' . $dir, $file_list, $ignore_dir);
                        }
                    }
                }
            }
            @closedir($handle);
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
 * 价格格式化
 *
 * @param int $price
 * @return string    $price_format
 */
function ds_price_format($price)
{
    $price_format = number_format($price, 2, '.', '');
    return $price_format;
}

/**
 * 价格格式化
 *
 * @param int $price
 * @return string    $price_format
 */
function ds_price_format_forlist($price)
{
    if ($price >= 10000) {
        return number_format(floor($price / 100) / 100, 2, '.', '') . lang('ten_thousand');
    } else {
        return lang('currency') . $price;
    }
}


/**
 * 通知邮件/通知消息 内容转换函数
 *
 * @param string $message 内容模板
 * @param array $param 内容参数数组
 * @return string 通知内容
 */
function ds_replace_text($message, $param)
{
    if (!is_array($param))
        return false;
    foreach ($param as $k => $v) {
        $message = str_replace('{$' . $k . '}', $v, $message);
    }
    return $message;
}

/** @noinspection InconsistentLineSeparators */

/**
 * 字符串切割函数，一个字母算一个位置,一个字算2个位置
 *
 * @param string $string 待切割的字符串
 * @param int $length 切割长度
 * @param string $dot 尾缀
 */
function str_cut($string, $length, $dot = '')
{
    $string = str_replace(array(
        '&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;',
        '&middot;', '&hellip;'
    ), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
    $strlen = strlen($string);
    if ($strlen <= $length)
        return $string;
    $maxi = $length - strlen($dot);
    $strcut = '';

    $n = $tn = $noc = 0;
    while ($n < $strlen) {
        $t = ord($string[$n]);
        if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1;
            $n++;
            $noc++;
        } elseif (194 <= $t && $t <= 223) {
            $tn = 2;
            $n += 2;
            $noc += 2;
        } elseif (224 <= $t && $t < 239) {
            $tn = 3;
            $n += 3;
            $noc += 2;
        } elseif (240 <= $t && $t <= 247) {
            $tn = 4;
            $n += 4;
            $noc += 2;
        } elseif (248 <= $t && $t <= 251) {
            $tn = 5;
            $n += 5;
            $noc += 2;
        } elseif ($t == 252 || $t == 253) {
            $tn = 6;
            $n += 6;
            $noc += 2;
        } else {
            $n++;
        }
        if ($noc >= $maxi)
            break;
    }
    if ($noc > $maxi)
        $n -= $tn;
    $strcut = substr($string, 0, $n);
    $strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
    return $strcut . $dot;
}


/*
 * 重写$_SERVER['REQUREST_URI']
 */

function request_uri()
{
    if (isset($_SERVER['REQUEST_URI'])) {
        $uri = $_SERVER['REQUEST_URI'];
    } else {
        if (isset($_SERVER['argv'])) {
            $uri = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];
        } else {
            $uri = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
        }
    }
    return $uri;
}


/**
 * 取得商品默认大小图片
 *
 * @param string $key 图片大小 small
 * @return string
 */
function default_goodsimage($key = '')
{
    //$file = str_ireplace('.', '_' . $key . '.', config('default_goods_image'));
    $file = config('default_goods_image');
    return ATTACH_COMMON . '/' . $file;
}

function get_member_id_by_XDSKEY()
{
    $key = request()->header('X-DS-KEY');
    if (!$key) {
        return;
    }
    $mbusertoken_model = model('mbusertoken');
    $mb_user_token_info = $mbusertoken_model->getMbusertokenInfoByToken($key);
    if (empty($mb_user_token_info)) {
        return;
    } else {
        return $mb_user_token_info['member_id'];
    }
}

function get_member_idcard_image($member_image, $if_local = false)
{
    if ($member_image) {
        if ($if_local) {
            $upload_path = BASE_UPLOAD_PATH;
        } else {
            $upload_path = UPLOAD_SITE_URL;
        }
        if (!empty($member_image) && file_exists(BASE_UPLOAD_PATH . '/' . ATTACH_IDCARD_IMAGE . '/' . $member_image)) {
            return $upload_path . '/' . ATTACH_IDCARD_IMAGE . '/' . $member_image;
        }
    }

    return '';
}

/**
 * 取得用户头像图片
 *
 * @param string $member_avatar
 * @return string
 */
function get_member_avatar($member_avatar)
{

    if (empty($member_avatar)) {
        return UPLOAD_SITE_URL . '/' . ATTACH_COMMON . '/' . 'default_user_portrait.gif';
    } else {
        if (strlen(strstr($member_avatar, 'http'))) {
            return $member_avatar;
        } else {
            $file_http = db('config')->where('code', 'qiniu_http')->find();
            return $file_http['value'] . '/' . $member_avatar;
        }
    }
}

/**
 * 成员头像
 * @param string $member_id
 * @return string
 */
function get_member_avatar_for_id($id)
{
    if (file_exists(BASE_UPLOAD_PATH . '/' . ATTACH_AVATAR . '/avatar_' . $id . '.jpg')) {
        return UPLOAD_SITE_URL . '/' . ATTACH_AVATAR . '/avatar_' . $id . '.jpg';
    } else {
        if (config('default_user_portrait')) {
            return UPLOAD_SITE_URL . '/' . ATTACH_COMMON . '/' . config('default_user_portrait');
        } else {
            return UPLOAD_SITE_URL . '/' . ATTACH_COMMON . '/' . 'default_user_portrait.gif';
        }

    }
}


/**
 * 取得店铺标志
 *
 * @param string $img 图片名
 * @param string $type 查询类型 store_logo/store_avatar
 * @return string
 */
function get_store_logo($img, $type = 'store_avatar')
{
    if ($type == 'store_avatar') {
        if (empty($img)) {
            return UPLOAD_SITE_URL . '/' . ATTACH_COMMON . '/' . config('default_store_avatar');
        } else {
            $linfo = explode('_', $img);
            /*if (is_file(BASE_UPLOAD_PATH . '/' . ATTACH_STORE . '/' . $linfo['0'] . '/' . $img))
                return UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $linfo['0'] . '/' . $img;
            return UPLOAD_SITE_URL . '/' . ATTACH_COMMON . '/' . config('default_store_avatar');*/
            $file_http = db('config')->where('code', 'qiniu_http')->find();
            return $file_http['value'] . '/' . $img;


        }
    } elseif ($type == 'store_logo') {
        if (empty($img)) {
            return UPLOAD_SITE_URL . '/' . ATTACH_COMMON . '/' . config('default_store_logo');
        } else {
            $linfo = explode('_', $img);
            return UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $linfo['0'] . '/' . $img;
        }
    } elseif ($type == 'store_banner') {
        if (!empty($img)) {
            $linfo = explode('_', $img);
            return UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $linfo['0'] . '/' . $img;
        }
    }
}

function get_adv_code($adv_code)
{
    if (!file_exists(BASE_UPLOAD_PATH . '/' . ATTACH_ADV . '/' . $adv_code)) {
        return UPLOAD_SITE_URL . '/' . default_goodsimage('normal');
    } else {
        return UPLOAD_SITE_URL . '/' . ATTACH_ADV . '/' . $adv_code;
    }
}

function get_appadv_code($adv_code)
{
    if (!file_exists(BASE_UPLOAD_PATH . '/' . ATTACH_APPADV . '/' . $adv_code)) {
        return UPLOAD_SITE_URL . '/' . default_goodsimage('normal');
    } else {
        return UPLOAD_SITE_URL . '/' . ATTACH_APPADV . '/' . $adv_code;
    }
}

/**
 * 获取店铺分类图标
 * @param type $storeclass_id
 * @return type
 */
function get_storeclass_pic($storeclass_id)
{
    if (!file_exists(BASE_UPLOAD_PATH . '/' . ATTACH_STORECLASS . '/' . 'storeclass-pic-' . $storeclass_id . '.png')) {
        return UPLOAD_SITE_URL . '/' . default_goodsimage('normal');
    } else {
        return UPLOAD_SITE_URL . '/' . ATTACH_STORECLASS . '/' . 'storeclass-pic-' . $storeclass_id . '.png';
    }
}

/**
 * 获取用户相册图片
 * @param type $user_id
 * @param type $ap_cover
 * @return type
 */
function get_snsalbumpic($user_id, $ap_cover)
{
    if (!file_exists(BASE_UPLOAD_PATH . '/' . ATTACH_MALBUM . '/' . $user_id . '/' . $ap_cover)) {
        return UPLOAD_SITE_URL . '/' . default_goodsimage('normal');
    } else {
        return UPLOAD_SITE_URL . '/' . ATTACH_MALBUM . '/' . $user_id . '/' . $ap_cover;
    }
}


/**
 * 获取开店申请图片
 */
function get_store_joinin_imageurl($image_name = '')
{
    $config = db('config')->where('code', 'qiniu_http')->find();
    return  $config['value'].'/'.$image_name;
}


/**
 * 获取运单图片地址
 */
function get_waybill_imageurl($image_name = '')
{
    $image_path = '/' . ATTACH_WAYBILL . '/' . $image_name;
    if (is_file(BASE_UPLOAD_PATH . $image_path)) {
        return UPLOAD_SITE_URL . $image_path;
    } else {
        return UPLOAD_SITE_URL . '/' . default_goodsimage('240');
    }
}

/**
 * 取得随机数
 *
 * @param int $length 生成随机数的长度
 * @param int $numeric 是否只产生数字随机数 1是0否
 * @return string
 */
function random($length, $numeric = 0)
{
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}


/**
 * sns表情标示符替换为html
 */
function parsesmiles($message)
{
    $message = htmlspecialchars_decode($message);
    if (preg_match("/^\[goods\](.)+\[\/goods\]$/", $message)) {
        $chat_goods = json_decode(preg_replace("/\[\/?goods\]/", "", $message), true);
        $message = '<div class="dstouch-chat-product"> <a href="' . HOME_SITE_URL . '/goods/index?goods_id=' . $chat_goods['goods_id'] . '" target="_blank"><div class="goods-pic"><img src="' . $chat_goods['goods_image'] . '" alt=""/></div><div class="goods-info"><div class="goods-name">' . $chat_goods['goods_name'] . '</div><div class="goods-price">￥' . $chat_goods['goods_price'] . "</div></div></a> </div>";
    } else {
        $file = EXTEND_PATH . '/smilies.php';
        if (file_exists($file)) {
            include $file;
            if (!empty($smilies_array) && is_array($smilies_array)) {
                $imagesurl = PLUGINS_SITE_ROOT . '/js' . '/smilies' . '/images' . '/';
                $replace_arr = array();
                foreach ($smilies_array['replacearray'] AS $key => $smiley) {
                    $replace_arr[$key] = '<img src="' . $imagesurl . $smiley['imagename'] . '" title="' . $smiley['desc'] . '" border="0" alt="' . $imagesurl . $smiley['desc'] . '" />';
                }

                $message = preg_replace($smilies_array['searcharray'], $replace_arr, $message);
            }
        }
    }

    return $message;
}


/**
 * 延时加载分页功能，判断是否有更多连接和limitstart值和经过验证修改的$delay_eachnum值
 * @param int $delay_eachnum 延时分页每页显示的条数
 * @param int $delay_page 延时分页当前页数
 * @param int $count 总记录数
 * @param bool $ispage 是否在分页模式中实现延时分页(前台显示的两种不同效果)
 * @param int $page_nowpage 分页当前页数
 * @param int $page_eachnum 分页每页显示条数
 * @param int $page_limitstart 分页初始limit值
 * @return array array('hasmore'=>'是否显示更多连接','limitstart'=>'加载的limit开始值','delay_eachnum'=>'经过验证修改的$delay_eachnum值');
 */
function lazypage($delay_eachnum, $delay_page, $count, $ispage = false, $page_nowpage = 1, $page_eachnum = 1, $page_limitstart = 1)
{
    //是否有多余
    $hasmore = true;
    $limitstart = 0;
    if ($ispage == true) {
        if ($delay_eachnum < $page_eachnum) {//当延时加载每页条数小于分页的每页条数时候实现延时加载，否则按照普通分页程序流程处理
            $page_totlepage = ceil($count / $page_eachnum);
            //计算limit的开始值
            $limitstart = $page_limitstart + ($delay_page - 1) * $delay_eachnum;
            if ($page_totlepage > $page_nowpage) {//当前不为最后一页
                if ($delay_page >= $page_eachnum / $delay_eachnum) {
                    $hasmore = false;
                }
                //判断如果分页的每页条数与延时加载每页的条数不能整除的处理
                if ($hasmore == false && $page_eachnum % $delay_eachnum > 0) {
                    $delay_eachnum = $page_eachnum % $delay_eachnum;
                }
            } else {//当前最后一页
                $showcount = ($page_totlepage - 1) * $page_eachnum + $delay_eachnum * $delay_page; //已经显示的记录总数
                if ($count <= $showcount) {
                    $hasmore = false;
                }
            }
        } else {
            $hasmore = false;
        }
    } else {
        if ($count <= $delay_page * $delay_eachnum) {
            $hasmore = false;
        }
        //计算limit的开始值
        $limitstart = ($delay_page - 1) * $delay_eachnum;
    }

    return array('hasmore' => $hasmore, 'limitstart' => $limitstart, 'delay_eachnum' => $delay_eachnum);
}


/**
 * 返回以原数组某个值为下标的新数据
 *
 * @param array $array
 * @param string $key
 * @param int $type 1一维数组2二维数组
 * @return array
 */
function array_under_reset($array, $key, $type = 1)
{
    if (is_array($array)) {
        $tmp = array();
        foreach ($array as $v) {
            if ($type === 1) {
                $tmp[$v[$key]] = $v;
            } elseif ($type === 2) {
                $tmp[$v[$key]][] = $v;
            }
        }
        return $tmp;
    } else {
        return $array;
    }
}

/**
 * KV缓存 读
 *
 * @param string $key 缓存名称
 * @param boolean $callback 缓存读取失败时是否使用回调 true代表使用cache.model中预定义的缓存项 默认不使用回调
 * @param callable $callback 传递非boolean值时 通过is_callable进行判断 失败抛出异常 成功则将$key作为参数进行回调
 * @return mixed
 */
function rkcache($key, $callback = false)
{
    $value = cache($key);
    if (empty($value) && $callback !== false) {
        if ($callback === true) {
            $callback = array(model('cache'), 'call');
        }

        if (!is_callable($callback)) {
            exception('Invalid rkcache callback!');
        }
        $value = call_user_func($callback, $key);
        wkcache($key, $value);
    }
    return $value;
}

/**
 * KV缓存 写
 *
 * @param string $key 缓存名称
 * @param mixed $value 缓存数据 若设为否 则下次读取该缓存时会触发回调（如果有）
 * @param int $expire 缓存时间 单位秒 null代表不过期
 * @return boolean
 */
function wkcache($key, $value, $expire = 7200)
{
    return cache($key, $value, $expire);
}

/**
 * KV缓存 删
 *
 * @param string $key 缓存名称
 * @return boolean
 */
function dkcache($key)
{
    return cache($key, NULL);
}

/**
 * 读取缓存信息
 *
 * @param string $key 要取得缓存键
 * @param string $prefix 键值前缀
 * @return array/bool
 */
function rcache($key = null, $prefix = '')
{
    if ($key === null || !config('cache_open'))
        return array();
    if (!empty($prefix)) {
        $name = $prefix . $key;
    } else {
        $name = $key;
    }
    $cache_info = cache($name);
    //如果name值不存在，则默认返回 false。
    return $cache_info;
}

/**
 * 写入缓存
 *
 * @param string $key 缓存键值
 * @param array $data 缓存数据
 * @param string $prefix 键值前缀
 * @param int $expire 缓存周期  单位分，0为永久缓存
 * @return bool 返回值
 */
function wcache($key = null, $data = array(), $prefix = '', $expire = 3600)
{
    if ($key === null || !config('cache_open') || !is_array($data))
        return;

    if (!empty($prefix)) {
        $name = $prefix . $key;
    } else {
        $name = $key;
    }
    $cache_info = cache($name, $data, $expire);
    //如果设置成功返回true，否则返回false。
    return $cache_info;
}

/**
 * 删除缓存
 * @param string $key 缓存键值
 * @param string $prefix 键值前缀
 * @return boolean
 */
function dcache($key = null, $prefix = '')
{
    if ($key === null || !config('cache_open'))
        return true;
    if (!empty($prefix)) {
        $name = $prefix . $key;
    } else {
        $name = $key;
    }
    return cache($name, NULL);
}


/**
 * 输出聊天信息
 *
 * @return string
 */
function get_chat()
{
    return Chat::getChatHtml();
}


/**
 * 验证是否为平台店铺
 *
 * @return boolean
 */
function check_platform_store()
{
    return session('is_platform_store');
}

/**
 * 验证是否为平台店铺 并且绑定了全部商品类目
 *
 * @return boolean
 */
function check_platform_store_bindingall_goodsclass()
{

    return check_platform_store() && session('bind_all_gc');
}

/**
 * 生成20位编号(时间+微秒+随机数+会员ID%1000)，该值会传给第三方支付接口
 * 长度 =12位 + 3位 + 2位 + 3位  = 20位
 * 1000个会员同一微秒提订单，重复机率为1/100
 * @return string
 */

function makePaySn($member_id)
{
    return date('ymdHis', time()) . sprintf('%03d', (float)microtime() * 1000) . mt_rand(10, 99) . sprintf('%03d', intval($member_id) % 1000);
}

/**
 * 获得店铺状态样式名称
 * @param $param array $store_info
 * @return string
 */
function get_store_state_classname($store_info)
{
    $result = 'open';
    if (intval($store_info['store_state']) === 1) {
        $store_endtime = intval($store_info['store_endtime']);
        if ($store_endtime > 0) {
            if ($store_endtime < TIMESTAMP) {
                $result = 'expired';
            } elseif (($store_endtime - 864000) < TIMESTAMP) {
                //距离到期10天
                $result = 'expire';
            }
        }
    } else {
        $result = 'close';
    }
    return $result;
}

/**
 * 将字符部分加密并输出
 * @param unknown $str
 * @param unknown $start 从第几个位置开始加密(从1开始)
 * @param unknown $length 连续加密多少位
 * @return string
 */
function encrypt_show($str, $start, $length)
{
    $end = $start - 1 + $length;
    $array = str_split($str);
    foreach ($array as $k => $v) {
        if ($k >= $start - 1 && $k < $end) {
            $array[$k] = '*';
        }
    }
    return implode('', $array);
}

/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug 调试开启 默认false
 * @return mixed
 */
function do_http_request($url, $method = "GET", $postfields = null, $headers = array(), $debug = false)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
}

/**
 * Layer 提交成功返回函数
 * @param type $message
 */
function dsLayerOpenSuccess($msg = '', $url = '')
{
//    echo "<script>var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index);parent.location.reload();</script>";
    $url_js = empty($url) ? "parent.location.reload();" : "parent.location.href='" . $url . "';";

    $str = "<script>";
    $str .= "parent.layer.alert('" . $msg . "',{yes:function(index, layero){" . $url_js . "},cancel:function(index, layero){" . $url_js . "}});";
    $str .= "</script>";
    echo $str;
    exit;
}

/**
 * Layer 提交成功返回函数
 * @param type $message
 */
function dsLayerOpenSuccessNew($msg = '', $url = '')
{
//    echo "<script>var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index);parent.location.reload();</script>";
    $url_js = empty($url) ? "parent.location.reload();" : "parent.layer.closeAll();location.href='" . $url . "';";

    $str = "<script>";
//    $str .= "parent.layer.alert('".$msg."',{yes:function(index, layero){".$url_js."},cancel:function(index, layero){".$url_js."}});";
    $str .= "parent.layer.alert('" . $msg . "',{yes:function(index, layero){" . $url_js . "},cancel:function(index, layero){" . $url_js . "}});";
    $str .= "</script>";
    echo $str;
    exit;
}

/**
 * 移除微信昵称中的emoji字符
 * @param type $nickname
 * @return type
 */
function removeEmoji($nickname)
{
    $clean_text = "";
    // Match Emoticons
    $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $clean_text = preg_replace($regexEmoticons, '', $nickname);
    // Match Miscellaneous Symbols and Pictographs
    $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $clean_text = preg_replace($regexSymbols, '', $clean_text);
    // Match Transport And Map Symbols
    $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
    $clean_text = preg_replace($regexTransport, '', $clean_text);
    // Match Miscellaneous Symbols
    $regexMisc = '/[\x{2600}-\x{26FF}]/u';
    $clean_text = preg_replace($regexMisc, '', $clean_text);
    // Match Dingbats
    $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
    $clean_text = preg_replace($regexDingbats, '', $clean_text);
    //截取指定长度的昵称
    $clean_text = ds_substing($clean_text, 0, 20);
    return trim($clean_text);
}

/**
 * 截取指定长度的字符
 * @param type $string 内容
 * @param type $start 开始
 * @param type $length 长度
 * @return type
 */
function ds_substing($string, $start = 0, $length = 80)
{
    $string = strip_tags($string);
    $string = preg_replace('/\s/', '', $string);
    return mb_substr($string, $start, $length);
}

/**
 * 针对批量删除进行处理  '1,2,3' 转换为数组批量删除
 * @param type $ids
 * @return boolean
 */
function ds_delete_param($ids)
{
    //转换为数组
    $ids_array = explode(',', $ids);
    //数组值转为整数型
    $ids_array = array_map("intval", $ids_array);
    if (empty($ids_array) || in_array(0, $ids_array)) {
        return FALSE;
    } else {
        return $ids_array;
    }
}

/**
 * 七牛云
 * @return String 图片的完整URL
 */
function upload_qiniu($img_name)
{
    $qiniu_accesskey = db('config')->where('code', 'qiniu_accesskey')->find();
    $qiniu_secretKey = db('config')->where('code', 'qiniu_secretKey')->find();
    $qiniu_bucket = db('config')->where('code', 'qiniu_bucket')->find();
    $qiniu_http = db('config')->where('code', 'qiniu_http')->find();

    $file = request()->file($img_name);
    // 要上传图片的本地路径
    $filePath = $file->getRealPath();
    $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
    // 上传到七牛后保存的文件名
    $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
    require_once APP_PATH . '/../vendor/php-qiniu/qiniu/php-sdk/autoload.php';
    // 需要填写你的 Access Key 和 Secret Key
    $accessKey = $qiniu_accesskey['value'];

    $secretKey = $qiniu_secretKey['value'];
    // 构建鉴权对象
    $auth = new Auth($accessKey, $secretKey);
    // 要上传的空间
    $bucket = $qiniu_bucket['value'];
    $domain = $qiniu_http['value'];

    $token = $auth->uploadToken($bucket);
    // 初始化 UploadManager 对象并进行文件的上传
    $uploadMgr = new UploadManager();
    // 调用 UploadManager 的 putFile 方法进行文件的上传
    list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
    if ($err !== null) {
        return ["err" => 1, "msg" => $err, "data" => ""];
    } else {
        //返回图片的完整URL

        return ["err" => 0, "msg" => "上传完成", "data" => $ret['key'], 'http' => $domain];
    }
}

#公告推送
function SendAll($message)
{

    require_once APP_PATH . '/../extend/JPush/autoload.php';

    // 构建鉴权对象
    $auth = new Jpush('f8fda95da1d7f5894955ec63', 'cd9b733d9179de75279edf16');

    $result = $auth->push()
        ->setPlatform('all') #推送平台
        ->addAllAudience()
        ->setNotificationAlert($message)  //你要推送的信息              
        ->send();
    return json_encode($result);  //返回发送结果
}


/**
 * 向指定设备推送消息
 */
function sendSpecial($regid, $message)
{
    require_once(BASE_RESOURCE_PATH . DS . 'JPush1' . DS . 'JPush.php');//引入框架加载包，有的版
    //本是autoload.php
    /*$client->appKey = '你的APPKey';
    $client->masterSecret = '你的masterSecret';*/
    $app_key = '你的APPKey';
    $master_secret = '你的masterSecret';
    $client = new JPush($app_key, $master_secret);
    $result = $client->push()->setPlatform('all')  //设备：all表示所有，可以是
    // ios/android
    ->addRegistrationId($regid)  //你要推送的设备号/用户
    ->setNotificationAlert($message)
        ->send();
    echo json_encode($result);
}


/**
 * @description: 生成邀请码  @MrLiu
 * @return string
 */
function create_invite_code()
{
    $uniqueStr = strtoupper(substr(md5(microtime(true)), 0, 6));
    return $uniqueStr;
}

/**
 * @description: 客户类型  @MrLiu
 * @param string $key
 * @return array|mixed|string
 */
function member_type($key = '')
{
    $type = array(
        '汽修连锁', '4S店', '轮胎店', '修理厂', '学校', '实验室',
        '汽车之家', '配件厂家', '耗材厂家', '油品厂家', '集团客户',
        '汽保商', '其他',
    );
    if (empty($key)) {
        return $type;
    } else {
        return isset($type[$key]) ? $type[$key] : '键值不存在';
    }
}

/**
 * @description: 验证是否可以收货
 * @param string $key
 * @return array|mixed|string
 */
function check_big_order_status($user_id, $app_order_id)
{
    //找到当前大订单
    $big_order = db('app_order')->where(['app_order_id' => $app_order_id])->find();
    $big = explode(',', $big_order['order_ids']);

    //判断其他订单是否收货了  
    if (!empty($big)) {
        $all_order_end = true;
        foreach ($big as $key => $value) {
            $recei = db('order')->where(['order_id' => $value])->find();

            //判断订单是否已发货  =30 判断商品已退货
            if ($recei['order_state'] >= 30) {

                if ($recei['order_state'] == 40) {
                    //判断是否全部收货
                } else {
                    //去判断商品是否有退换货
                    // $big_goods = explode(',',$big_order['goods_ids']);
                    $all_goods_end = true;

                    //通过订单id查订单详情表
                    $rec_info = db('ordergoods')->where(['order_id' => $value])->select();

                    foreach ($rec_info as $ke => $rec_item) {
                        //找到rec详情里面的退换货状态
                        $return_goods = db('ordergoods')->where(['rec_id' => $rec_item['rec_id']])->find();
                        //判断是否在退换货中
                        // if($return_goods['return_status'] != 4 && $return_goods['return_status'] != 0){
                        if ($return_goods['return_status'] != 4) {
                            //商品未结束
                            $all_goods_end = false;
                            break;
                        }
                    }
                    //如果商品有在退换货，订单没有结束
                    if (!$all_goods_end) {
                        $all_order_end = false;
                        break;
                    }
                }

            } elseif ($recei['order_state'] == 20) {
                //判断是否退款中
                if ($recei['refund_state'] != 3) {
                    $all_order_end = false;
                    break;
                }
            }
        }

        //判断所有子订单是否都已完成
        if ($all_order_end) {
            db('app_order')->where(['app_order_id' => $app_order_id])->update(['order_status' => 2]);
        }
    }


}


/**
 * 是否是手机号码
 *
 * @param string $phone
 * @return boolean
 */
function is_mobile($phone)
{
    if (strlen($phone) != 11 || !preg_match('/^1[3|4|5|7|8|9][0-9]\d{4,8}$/', $phone)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 是否为一个合法的email
 *
 * @param sting $email
 * @return boolean
 */
function is_email($email)
{
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

//判断银行卡位数
function checkBankNo($bankNo)
{
    if (preg_match('/^{16,19}$/i', $bankNo)) {
        return true;
    } else {
        return false;
    }
}

//公共方法 获取分类名称
function getClassName($goods_list)
{
    foreach ($goods_list as $key => $value) {
        //获取分类名称
        $name = db('goodsclass')->where(['gc_id' => $value['gc_id_3']])->find();
        $name1 = db('goodsclass')->where(['gc_id' => $value['gc_id_2']])->find();
        $name2 = db('goodsclass')->where(['gc_id' => $value['gc_id_1']])->find();

        if (!empty($name2) && !empty($name1) && !empty($name)) {
            $goods_list[$key]['class_name'] = $name2['gc_name'] . '>' . $name1['gc_name'] . '>' . $name['gc_name'];
        } elseif (!empty($name2) && !empty($name1)) {
            $goods_list[$key]['class_name'] = $name2['gc_name'] . '>' . $name1['gc_name'];
        } else {
            $goods_list[$key]['class_name'] = $name2['gc_name'];
        }
    }
    return $goods_list;

}

//公共方法 获取分类信息
function getClassNameInfo($gc_id)
{
    //处理分类
    $class = db('goodsclass')->where(['gc_id' => $gc_id])->find();
    if (empty($class['gc_parent_id'])) {
        //没父值的话就是一级分类id
        $param['gc_one_id'] = $class['gc_id'];
        $param['gc_id'] = $class['gc_id'];
        $param['class_name'] = $class['gc_name'];
    } else {
        //有父值的话再往上找
        $class_one = db('goodsclass')->where(['gc_id' => $class['gc_parent_id']])->find();
        if (empty($class_one['gc_parent_id'])) {
            $param['gc_one_id'] = $class_one['gc_id'];
            $param['gc_two_id'] = $class['gc_id'];
            $param['gc_id'] = $class['gc_id'];
            $param['class_name'] = $class_one['gc_name'] . '>' . $class['gc_name'];
        } else {
            $class_two = db('goodsclass')->where(['gc_id' => $class_one['gc_parent_id']])->find();
            $param['gc_one_id'] = $class_two['gc_id'];
            $param['gc_two_id'] = $class_one['gc_id'];
            $param['gc_three_id'] = $class['gc_id'];
            $param['gc_id'] = $class['gc_id'];
            $param['class_name'] = $class_two['gc_name'] . '>' . $class_one['gc_name'] . '>' . $class['gc_name'];
        }
    }
    return $param;

}

function checkCode($phone, $member_code)
{
    if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
        return json_fail_return('手机号格式不正确');
    }
    if ($member_code != Session::get('code')) {
        return false;
    } else {
        return true;
    }
}

//实时查询物流单号  //查询的快递公司的编码， 一律用小写字母  //查询的快递单号
function get_query_logistics($logistics_com, $logistics_num)
{
    //参数设置
    $post_data = array();
    $post_data["customer"] = '52C6862EDCDB88C032C02728370C3683';
    $key = 'nbWstFfP4769';

    $params = [
        'com' => $logistics_com,
        'num' => $logistics_num
    ];
    $params_info = json_encode($params);
    $post_data["param"] = $params_info;

    $url = 'http://poll.kuaidi100.com/poll/query.do';
    $post_data["sign"] = md5($post_data["param"] . $key . $post_data["customer"]);
    $post_data["sign"] = strtoupper($post_data["sign"]);
    $o = "";
    foreach ($post_data as $k => $v) {
        $o .= "$k=" . urlencode($v) . "&";       //默认UTF-8编码格式
    }
    $post_data = substr($o, 0, -1);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//它就将使用PHP curl获取页面内容或提交数据，作为变量储存，而不是直接输出。
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $result = curl_exec($ch);
    curl_close($ch); //关闭一个cURL会话
    $info = json_decode($result, true);

    if (!empty($info['data'])) {
        return $info['data'];
    } else {
        return 1;
    }

}

//转xml格式
function arrayToXml($arr)
{
    $xml = "<?xml version='1.0' encoding='utf-8'?>";
    $xml .= "<ScanMerchantInQueryRequest>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<$key>$val</$key>";
        } else
            $xml .= "<$key>$val</$key>";
    }
    $xml .= "</ScanMerchantInQueryRequest>";
    return $xml;
}

//生成随机字符串    
function createNonceStr($length = 16)
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

function getWeek()
{
    return [
        1 => '周一',
        2 => '周二',
        3 => '周三',
        4 => '周四',
        5 => '周五',
        6 => '周六',
        7 => '周日',
    ];
}

function getTime()
{
    $timeArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
    foreach ($timeArr as $v) {
        if (strlen($v) == 2) {
            $timeArr2[] = $v . ':00';
            if ($v < 24) {
                $timeArr2[] = $v . ':30';
            }
        } else {
            $timeArr2[] = '0' . $v . ':00';
            $timeArr2[] = '0' . $v . ':30';
        }
    }
    return $timeArr2;
}


//获取服务单类型  
function getSorderText($status)
{
    switch ($status) {
        case 1:
            return '安装';
            break;
        case 2:
            return '维修';
            break;
        case 3:
            return '拆移机';
            break;
        default:
            return '保养';
            break;
    }
}

//获取服务单类型
function getSorderStatusText($status)
{
    switch ($status) {
        case -1:
            return '已取消';
            break;
        case 1:
            return '待审核';
            break;
        case 2:
            return '待支付';
            break;
        case 3:
            return '待派单';
            break;
        case 4:
            return '已完成';
            break;
        case 5:
            return '已退款';
            break;
        case 6:
            return '未通过';
            break;
        case 7:
            return '进行中';
            break;

        default:
            break;
    }
}

//获取订单zhuangt  
function getSorderStatus($status)
{
    switch ($status) {
        case -1:
            return '取消订单';
            break;
        case 0:
            return '已作废';
            break;
        case 1:
            return '待审核';
            break;
        case 2:
            return '待支付';
            break;
        case 3:
            return '支付完成';
            break;
        case 4:
            return '已完成';
            break;
        case 5:
            return '已退款';
            break;
        case 6:
            return '未通过';
            break;
        default:
            return '疑问单';
            break;
    }
}

//获取用户身份
function getUserIdentity($type)
{
    switch ($type) {
        case 0:
            return '普通用户';
            break;
        case 1:
            return '供应商';
            break;
        case 2:
            return '运营商';
            break;
        case 3:
            return '运营商职员';
            break;
        case 4:
            return '供应商职员';
            break;
        case 5:
            return '运营商客服';
            break;
        case 6:
            return '运营商技术人员';
            break;
        case 7:
            return '散户技术人员';
            break;
        case 8:
            return '大客户';
            break;
        case 9:
            return '平台用户';
            break;
        default:
            return '平台客服';
            break;
    }
}

#预订单返回分类名称
function getBuyClass($mansong)
{
    //获取分类名称
    $name = db('goodsclass')->where(['gc_id' => $mansong['gc_three_id']])->find();
    $name1 = db('goodsclass')->where(['gc_id' => $mansong['gc_two_id']])->find();
    $name2 = db('goodsclass')->where(['gc_id' => $mansong['gc_one_id']])->find();
    if (!empty($name2) && !empty($name1) && !empty($name)) {
        $class_name = $name2['gc_name'] . '>' . $name1['gc_name'] . '>' . $name['gc_name'];
    } elseif (!empty($name2) && !empty($name1)) {
        $class_name = $name2['gc_name'] . '>' . $name1['gc_name'];
    } else {
        $class_name = $name2['gc_name'];
    }
    return $class_name;
}

//根据身份证号获取性别
function getSex($idcard)
{
    if (empty($idcard)) return null;
    return substr($idcard, (strlen($idcard) == 15 ? -2 : -1), 1) % 2 ? '1' : '0'; //1为男 2为女
}

#身份证号获取生日
function getIDCardInfo($IDCard)
{
    $result['error'] = 0;//0：未知错误，1：身份证格式错误，2：无错误
    $result['flag'] = '';//0标示成年，1标示未成年
    $result['tdate'] = '';//生日，格式如：2012-11-15<br>　　　　　
    if (!preg_match("/^[1-9]([0-9a-zA-Z]{17}|[0-9a-zA-Z]{14})$/i", $IDCard)) {
        $result['error'] = 1;
        return $result;
    } else {
        if (strlen($IDCard) == 18) {
            $tyear = intval(substr($IDCard, 6, 4));
            $tmonth = intval(substr($IDCard, 10, 2));
            $tday = intval(substr($IDCard, 12, 2));
            $tdate = $tyear . "-" . $tmonth . "-" . $tday;
            if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
                $flag = 0;
            } elseif ($tmonth < 0 || $tmonth > 12) {
                $flag = 0;
            } elseif ($tday < 0 || $tday > 31) {
                $flag = 0;
            } else {
                $tdate = $tyear . "-" . $tmonth . "-" . $tday;
                if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60) {
                    $flag = 0;
                } else {
                    $flag = 1;
                }
            }
        } elseif (strlen($IDCard) == 15) {
            $tyear = intval("19" . substr($IDCard, 6, 2));
            $tmonth = intval(substr($IDCard, 8, 2));
            $tday = intval(substr($IDCard, 10, 2));
            if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
                $flag = 0;
            } elseif ($tmonth < 0 || $tmonth > 12) {
                $flag = 0;
            } elseif ($tday < 0 || $tday > 31) {
                $flag = 0;
            } else {
                $tdate = $tyear . "-" . $tmonth . "-" . $tday;
                if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60) {
                    $flag = 0;
                } else {
                    $flag = 1;
                }
            }
        }
    }
    $result['error'] = 2;//0：未知错误，1：身份证格式错误，2：无错误
    $result['isAdult'] = $flag;//0标示成年，1标示未成年
    $result['birthday'] = $tdate;//生日日期
    return $result;
}

#生成纯二维码
function scerweima1($url = '', $filename, $avtar)
{
    $url = $url; //二维码内容
    $errorCorrectionLevel = 'L';//容错级别
    $matrixPointSize = 9;//生成图片大小
    //生成二维码图片
    vendor("qrcode.phpqrcode");

    $ad = 'code/' . $filename . '.jpg';
    \QRcode::png($url, $ad, $errorCorrectionLevel, $matrixPointSize, 2);

    $logo = $avtar;
    if (empty($avtar)) {
        $logo = 'http://33wang.douyinhot.com/46f5b202003131520417317.png';//准备好的logo图片
    }

    $QR = 'code/' . $filename . '.jpg';//已经生成的原始二维码图

    if ($logo !== FALSE) {
        $QR = imagecreatefromstring(file_get_contents($QR));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR);//二维码图片宽度
        $QR_height = imagesy($QR);//二维码图片高度
        $logo_width = imagesx($logo);//logo图片宽度
        $logo_height = imagesy($logo);//logo图片高度
        $logo_qr_width = $QR_width / 5;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        //重新组合图片并调整大小
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
            $logo_qr_height, $logo_width, $logo_height);
    }
    imagepng($QR, 'code/' . $filename . '.png');

    // 生成的文件名
    $fileName = 'code/' . $filename . '.png';

    $result = [
        'img_code' => $ad,
        'code' => $fileName
    ];
    return $result;

}

#生成海报二维码
function createPoster($config = array(), $filename = "")
{
    //如果要看报什么错，可以先注释调这个header
    if (empty($filename)) header("content-type: image/png");
    $imageDefault = array(
        'left' => 0,
        'top' => 0,
        'right' => 0,
        'bottom' => 0,
        'width' => 100,
        'height' => 100,
        'opacity' => 100
    );
    $textDefault = array(
        'text' => '',
        'left' => 0,
        'top' => 0,
        'fontSize' => 32,       //字号
        'fontColor' => '255,255,255', //字体颜色
        'angle' => 0,
    );
    $background = $config['background'];//海报最底层得背景
    //背景方法
    $backgroundInfo = getimagesize($background);
    $backgroundFun = 'imagecreatefrom' . image_type_to_extension($backgroundInfo[2], false);
    $background = $backgroundFun($background);
    $backgroundWidth = imagesx($background);  //背景宽度
    $backgroundHeight = imagesy($background);  //背景高度
    $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
    $color = imagecolorallocate($imageRes, 0, 0, 0);
    imagefill($imageRes, 0, 0, $color);
    // imageColorTransparent($imageRes, $color);  //颜色透明
    imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background));
    //处理了图片
    if (!empty($config['image'])) {
        foreach ($config['image'] as $key => $val) {
            $val = array_merge($imageDefault, $val);
            $info = getimagesize($val['url']);
            $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
            if ($val['stream']) {   //如果传的是字符串图像流
                $info = getimagesizefromstring($val['url']);
                $function = 'imagecreatefromstring';
            }
            $res = $function($val['url']);
            $resWidth = $info[0];
            $resHeight = $info[1];
            //建立画板 ，缩放图片至指定尺寸
            $canvas = imagecreatetruecolor($val['width'], $val['height']);
            imagefill($canvas, 0, 0, $color);
            //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
            imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
            $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left'];
            $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
            //放置图像
            imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']);//左，上，右，下，宽度，高度，透明度
        }
    }
    //处理文字
    if (!empty($config['text'])) {
        foreach ($config['text'] as $key => $val) {
            $val = array_merge($textDefault, $val);
            list($R, $G, $B) = explode(',', $val['fontColor']);
            $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
            $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
            $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
            imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
        }
    }
    //生成图片
    if (!empty($filename)) {
        $res = imagejpeg($imageRes, $filename, 90); //保存到本地
        imagedestroy($imageRes);
        if (!$res) return false;
        return $filename;
    } else {
        imagejpeg($imageRes);     //在浏览器上显示
        imagedestroy($imageRes);
    }
}
#根据商品id获取折扣信息
function getDiscounInfoByGoodId($goods_id){
    $xianshi_info = db('pxianshigoods')->where(['goods_id' => $goods_id])->find();
    //判断折扣活动是否异常
    $parms = [
        'xianshi_id' => $xianshi_info['xianshi_id'],
        'xianshi_end_time' => ['gt', time()]
    ];
    $xianshi = db('pxianshi')->where($parms)->find();
    if (!empty($xianshi)) {
        return $xianshi;
    }
    return [];
}
function get_parent_yys_id($member_id)
{
    $user_info = db('member')->where('member_id', $member_id)->find();
    if (empty($user_info['invite_store_id'])) {
        $store_id = '';
    } else {
        $store_id = $user_info['invite_store_id'];
    }
    return $store_id;
}


//下单支付判断优惠劵、积分使用情况
function getPayDiscount($memberId, $data, $place_price)
{

    // 如果用户使用优惠劵了  获取优惠劵的面额
    if (!empty($data['voucher_id'])) {
        // //获取优惠劵信息
        // $voucher_info = db('voucher_collection')->where(['id' => $data['voucher_id']])->find();
        // $voucher_price = $voucher_info['voucher_collection_price'];  #优惠劵的面额

        // #修改优惠劵使用状态
        // db('voucher_collection')->where(['id' => $data['voucher_id']])->update(['is_used' => 2]);
        //获取优惠劵信息
        $voucher_info = db('voucher')->where(['voucher_id' => $data['voucher_id']])->find();
        $voucher_price = $voucher_info['voucher_price'];
        //使用完改变优惠劵状态
        $voucher_list = db('voucher_collection')->where(['member_id' => $memberId, 'voucher_id' => $data['voucher_id'], 'is_used' => 1, 'is_send_del' => 0])->select();
        db('voucher_collection')->where(['id' => $voucher_list[0]['id']])->update(['is_used' => 2]);
    } else {
        $voucher_price = 0;
    }

    $fina_integral = 0; #使用了多少积分  
    $order_integral_price = 0; #积分抵扣了多少钱

    // //如果用户使用了积分
    if ($data['is_integrals'] == 1) {
        //获取比例  订单总金额/比例==商品总价转换为积分（积分）
        //现有积分 > 商品总价转换为积分（积分） -->(使用商品总价转换为积分（积分）)
        //现有积分 < 商品总价转换为积分（积分） -->(现有积分)
        //商品价格 - 上面的积分*比例
        $member_info = db('member')->where(['member_id' => $memberId])->find();
        //积分数量
        $integral_ratio = db('config')->where('code', 'integral_ratio')->find();
        //金额数量
        $price_ratio = db('config')->where('code', 'price_ratio')->find();
        //比例
        $bili = $price_ratio['value'] / $integral_ratio['value'];

        //获取商品总价可以转化多少积分  如果有优惠劵的话 减去优惠劵的面额   (商品总价需要用多少积分)
        $count_integral = ($place_price - $voucher_price) / $bili;

        //获取要使用多少积分
        if ($member_info['member_points'] > $count_integral) {
            $fina_integral = $count_integral;
        } else {
            $fina_integral = $member_info['member_points'];
        }

        $order_integral_price = ($fina_integral * $bili);

        // 订单总价 - 积分抵扣的金额 - 优惠劵减的金额
        $integral_price = $place_price - ($fina_integral * $bili) - $voucher_price;

        //下完单减积分
        $update_integral = $member_info['member_points'] - $fina_integral;
        db('member')->where(['member_id' => $memberId])->update(['member_points' => $update_integral]);

        #生成积分消费日志
        $points_info = [
            'pl_memberid' => $memberId,
            'pl_membername' => $member_info['member_name'],
            'pl_points' => '-' . $fina_integral,
            'pl_addtime' => time(),
            'pl_desc' => '购买商品',
            'pl_stage' => 'order',
            'pl_balance' => $update_integral
        ];
        db('pointslog')->insertGetId($points_info);
    } else {
        // 不使用   项目定制的总价 - 优惠劵减的金额
        $integral_price = $place_price - $voucher_price;
    }

    $return_data = [
        'integral_price' => $integral_price,
        'fina_integral' => $fina_integral,
        'order_integral_price' => $order_integral_price,
        'voucher_price' => $voucher_price
    ];
    return $return_data;
}

#极光用户注册 
function JmRegist($post)
{
    if (empty($post)) {
        return FALSE;
    } else {
        $str = 'f8fda95da1d7f5894955ec63' . ":" . 'cd9b733d9179de75279edf16';
        $base64 = base64_encode($str);
        $header[] = 'Content-Type:application/json';
        $header[] = 'Authorization: Basic ' . $base64;
        $nickname = substr($post['nickname'],0,3)."****".substr($post['nickname'],7,4);
        $data = [
            [
                'username' => $post['username'],
                'password' => 123456,
                'nickname' => $nickname,
                'signature' => $post['signature'],
            ]
        ];

        $data['0']['avatar'] = $post['avatar'] ? $post['avatar'] : 'http://33wang.douyinhot.com/cfe45202004231527382825.png';

        $post_data = json_encode($data);

        $res = curl($post_data, $header);

        if ($res[0]) {       //得到返回值--成功已否后面判断
            return $res;
        } else {          //未得到返回值--返回失败
            //return false;
            echo 0;
        }
    }
}

/**
 * Notes:极光用户更改头像
 * User: shen
 * Date: 2020/5/20
 * Time: 15:11
 * @param $post
 * @return bool|int|string
 */
function updateUserAvtar($post,$member_name)
{
    if (empty($post)) {
        return FALSE;
    } else {
        $str = 'f8fda95da1d7f5894955ec63' . ":" . 'cd9b733d9179de75279edf16';
        $base64 = base64_encode($str);
        $header[] = 'Content-Type:application/json';
        $header[] = 'Authorization: Basic ' . $base64;
       // 'avatar' => $post['file_name'],
        $data = [
            'avatar' => $post['file_name'],
        ];

        $post_data = json_encode($data);
        $res = put_curl($post_data, $header,$member_name);
        if (!$res) {       //得到返回值--成功已否后面判断
            return 'ok';
        } else {          //未得到返回值--返回失败
            echo 0;
        }
    }
}

#获取用户信息
function getJmText($username, $begin_time, $end_time)
{
    if (empty($begin_time)) {
        return FALSE;
    } else {
        #转义空格
        $new_begin_time = rawurlencode(date('Y-m-d H:i:s', $begin_time));
        $new_end_time = rawurlencode(date('Y-m-d H:i:s', $end_time));

        $str = 'f8fda95da1d7f5894955ec63' . ":" . 'cd9b733d9179de75279edf16';
        $base64 = base64_encode($str);
        $header[] = 'Content-Type:application/json';
        $header[] = 'Authorization: Basic ' . $base64;

        $str = "/v2/users/" . $username . '/messages?count=10&begin_time=' . $new_begin_time . '&end_time=' . $new_end_time;
        $action = "https://report.im.jpush.cn" . $str;

        $res = geturl($action, $header);
        var_dump($res);
        exit;
        if ($res[0]) {       //得到返回值--成功已否后面判断
            return $res;
        } else {          //未得到返回值--返回失败
            //return false;
            echo 0;
        }
    }
}

#get请求
function geturl($action, $httpHeader)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $action);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
    $output = curl_exec($ch);
    curl_close($ch);
    var_dump($output);
    exit;
    $output = json_decode($output, true);
    return $output;
}

#post请求
function curl($post_data, $httpHeader)
{
    $str = "/v1/users/";
    $action = "https://api.im.jpush.cn" . $str;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $action);
    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $ret = curl_exec($ch);
    if (false === $ret) {
        $ret = curl_errno($ch);
    }
    curl_close($ch);
    return $ret;
}

#put请求
function put_curl($post_data, $httpHeader,$member_name)
{
    $str = "/v1/users/{$member_name}";

    $action = "https://api.im.jpush.cn" . $str;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $action);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $ret = curl_exec($ch);
    if (false === $ret) {
        $ret = curl_errno($ch);
    }
    curl_close($ch);
    return $ret;
}


